<template>
	<div class="center-content">
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>个人信息</span>
				<el-button style="float: right; padding: 3px 0" type="text" @click="returnMain">返回主页</el-button>
			</div>

			<!-- 用户头像 -->
			<div class="user-image" @mouseenter="showEditOverlay = true" @mouseleave="showEditOverlay = false">
				<img :src="this.$store.state.user.img" alt="用户头像" />
				<!-- 悬浮遮罩层 -->
				<div class="image-overlay" v-show="showEditOverlay" @click="toFixImg">
					<div class="overlay-content">
						<i class="el-icon-camera"></i>
						<span>修改头像</span>
					</div>
				</div>
			</div>

			<!-- 用户信息 -->
			<div class="user-details">
				<div class="text item">
					<strong>用户名:</strong> {{ this.$store.state.user.username }}
				</div>
				<div class="text item">
					<strong>姓名:</strong> {{ this.$store.state.user.name || '未知' }}
				</div>
				<div class="text item">
					<strong>用户类型:</strong> {{ this.$store.state.user.usertype }}
				</div>
				<div class="text item">
					<strong>上次登录:</strong> {{ this.$store.state.user.lastLoginTime }}
				</div>
			</div>

			<div>
				<el-button @click="ifChangePassword" type="primary">
					{{ isChange ? '取消修改' : '修改密码' }}
				</el-button>
				<div v-if="isChange" class="password-form">
					<el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-position="left"
						label-width="80px" class="demo-ruleForm">
						<el-form-item label="新密码" prop="newPassword">
							<el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"
								show-password></el-input>
						</el-form-item>

						<el-form-item label="确认密码" prop="confirmPassword">
							<el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
								show-password></el-input>
						</el-form-item>

						<el-form-item>
							<el-button type="primary" @click="submitPassword" :loading="loading">
								确认修改
							</el-button>
							<el-button @click="cancelChange">取消</el-button>
						</el-form-item>
					</el-form>
				</div>
			</div>
		</el-card>

		<!-- 修改头像对话框 -->
		<el-dialog title="修改头像" :visible.sync="avatarDialogVisible" width="400px" center>
			<div class="avatar-upload">
				<!-- 方式1: 文件上传 -->
				<el-upload
					class="avatar-uploader"
					:action="uploadAction"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:before-upload="beforeAvatarUpload"
					:headers="uploadHeaders"
					:on-error="handleUploadError">
					<div class="upload-area">
						<i class="el-icon-plus avatar-uploader-icon"></i>
						<div>点击上传图片</div>
						<div class="upload-tip">支持 JPG、PNG 格式，大小不超过 2MB</div>
					</div>
				</el-upload>

				<!-- 方式2: 输入URL -->
				<div class="url-upload" style="margin-top: 20px;">
					<el-divider>或者</el-divider>
					<el-input v-model="avatarUrl" placeholder="输入图片URL地址" style="margin-bottom: 10px;">
						<template slot="append">
							<el-button @click="confirmAvatarUrl">确认</el-button>
						</template>
					</el-input>
				</div>
			</div>
			
			<div slot="footer" class="dialog-footer">
				<el-button @click="avatarDialogVisible = false">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import http from '../utils/request.js'
	export default {
		data() {
			// 确认密码验证规则
			const validateConfirmPassword = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'));
				} else if (value !== this.passwordForm.newPassword) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				showEditOverlay: false, // 控制悬浮遮罩显示
				avatarDialogVisible: false, // 控制修改头像对话框
				avatarUrl: '', // 头像URL
				uploadAction: '/userInfo/changeImg/uploadImg', // 文件上传地址
				uploadHeaders: {
					Authorization: 'Bearer ' + (localStorage.getItem('token') || '')
				},

				userInfo: null,
				isChange: false,
				loading: false,
				passwordForm: {
					newPassword: '',
					confirmPassword: ''
				},
				passwordRules: {
					newPassword: [{
							required: true,
							message: '请输入新密码',
							trigger: 'blur'
						},
						{
							min: 6,
							message: '密码长度至少6位',
							trigger: 'blur'
						}
					],
					confirmPassword: [{
							required: true,
							message: '请确认密码',
							trigger: 'blur'
						},
						{
							validator: validateConfirmPassword,
							trigger: 'blur'
						}
					]
				},
			}
		},
		methods: {
			returnMain() {
				this.$router.push("/")
			},
			
			// 点击修改头像
			toFixImg() {
				this.avatarDialogVisible = true;
				this.avatarUrl = this.$store.state.user.img || '';
			},

			// 上传前的验证
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isPNG = file.type === 'image/png';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG && !isPNG) {
					this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
					return false;
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
					return false;
				}
				return true;
			},

			// 上传成功处理
			handleAvatarSuccess(response, file) {
				console.log('上传成功响应:', response);
				if (response.code === 1) {
					const imageUrl = response.data.url || response.data;
					this.updateUserAvatar(imageUrl);
				} else {
					this.$message.error(response.msg || '上传失败');
				}
			},

			// 上传失败处理
			handleUploadError(error) {
				console.error('上传失败:', error);
				this.$message.error('图片上传失败，请重试');
			},

			// 确认URL方式修改头像
			confirmAvatarUrl() {
				if (!this.avatarUrl) {
					this.$message.warning('请输入图片URL');
					return;
				}
				
				// 简单验证URL格式
				if (!this.avatarUrl.startsWith('http')) {
					this.$message.warning('请输入有效的图片URL');
					return;
				}
				
				this.updateUserAvatarByUrl(this.avatarUrl);
			},

			// 通过URL更新用户头像
			async updateUserAvatarByUrl(imageUrl) {
				try {
					this.loading = true;
					
					// 调用URL方式更新头像接口
					const response = await http.post('/userInfo/changeImg/url', {
						img: imageUrl
					});

					if (response.data.code === 1) {
						this.$message.success('头像更新成功');
						this.updateUserAvatar(imageUrl);
					} else {
						this.$message.error(response.data.msg || '头像更新失败');
					}
				} catch (error) {
					console.error('URL方式更新头像失败:', error);
					this.$message.error('头像更新失败，请重试');
				} finally {
					this.loading = false;
				}
			},

			// 更新用户头像到store
			updateUserAvatar(imageUrl) {
				// 更新store中的用户信息
				this.$store.commit('updateUserAvatar', imageUrl);
				
				// 关闭对话框
				this.avatarDialogVisible = false;
				this.avatarUrl = '';
			},

			ifChangePassword() {
				this.isChange = !this.isChange;
				if (!this.isChange) {
					this.cancelChange();
				}
			},

			// 提交密码修改
			async submitPassword() {
				try {
					// 验证表单
					const valid = await this.$refs.passwordFormRef.validate();
					if (!valid) return;

					this.loading = true;

					// 调用修改密码API
					const response = await http.post('/userInfo/changePassword', {
						password: this.passwordForm.newPassword,
						username: this.$store.state.user.username
					});

					if (response.data.code === 1) {
						this.$message.success('密码修改成功,请重新登录');
						this.cancelChange();
						this.$router.push('/login');
					} else {
						this.$message.error(response.data.msg || '密码修改失败');
					}
				} catch (error) {
					console.error('修改密码失败:', error);
					this.$message.error('修改密码失败，请重试');
				} finally {
					this.loading = false;
				}
			},

			// 取消修改
			cancelChange() {
				this.isChange = false;
				this.passwordForm.newPassword = '';
				this.passwordForm.confirmPassword = '';

				// 清除验证状态
				if (this.$refs.passwordFormRef) {
					this.$refs.passwordFormRef.clearValidate();
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.center-content {
		width: 100%;
		height: 100vh;
		display: grid;
		place-items: center;
		background-color: #CCCCFF;

		.user-image {
			position: relative;
			width: 100px;
			height: 100px;
			margin: 0 auto 20px;
			border-radius: 50%;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				transform: scale(1.05);
			}

			img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.image-overlay {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.6);
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
				transition: all 0.3s ease;

				.overlay-content {
					text-align: center;
					
					i {
						font-size: 24px;
						display: block;
						margin-bottom: 5px;
					}
					
					span {
						font-size: 12px;
					}
				}

				&:hover {
					background: rgba(0, 0, 0, 0.7);
				}
			}
		}

		.user-details {
			.text.item {
				margin-bottom: 12px;
				padding: 8px 0;
				border-bottom: 1px solid #eee;

				strong {
					display: inline-block;
					width: 80px;
					color: #666;
				}
			}

			.loading {
				text-align: center;
				color: #999;
				padding: 20px;
			}
		}
	}

	// 头像上传样式
	.avatar-uploader {
		text-align: center;
		
		.upload-area {
			border: 2px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
			padding: 30px 0;
			transition: border-color 0.3s;

			&:hover {
				border-color: #409EFF;
			}

			.avatar-uploader-icon {
				font-size: 28px;
				color: #8c939d;
				display: block;
				margin-bottom: 10px;
			}

			.upload-tip {
				font-size: 12px;
				color: #8c939d;
				margin-top: 5px;
			}
		}
	}

	.text {
		font-size: 14px;
	}

	.clearfix:before,
	.clearfix:after {
		display: table;
		content: "";
	}

	.clearfix:after {
		clear: both
	}

	.box-card {
		width: 480px;
	}
</style>